package com.my.socket.nio.v4;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 * Created by ZhongGang
 * at 2018/6/29 16:27
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector acceptSelector;
    private Selector readSelector;
    private Selector writeSelector;
    private ServerSocketChannel serverSocketChannel;

    public Server(String host, int port) throws Exception {
        SelectorProvider selectorProvider = SelectorProvider.provider();
        this.acceptSelector = selectorProvider.openSelector();
        this.readSelector = selectorProvider.openSelector();
        this.writeSelector = selectorProvider.openSelector();

        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.bind(new InetSocketAddress(host, port));
        this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
    }

    public void startup() {
        new Thread(new AcceptTask(this.acceptSelector, this.readSelector, this.writeSelector), "accept-thread").start();
        new Thread(new ReadTask(this.acceptSelector, this.readSelector, this.writeSelector), "read-thread").start();
//        new Thread(new WriteTask(this.acceptSelector, this.readSelector, this.writeSelector), "write-thread").start();
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        server.startup();
        LOGGER.info("server startup at {}:{}", "127.0.0.1", 9999);
    }

}
